const {task, src, watch, series, parallel, dest} = require('gulp');
const glob = require('glob');
const clean = require('gulp-clean');
const uglify = require('gulp-uglify');
const babel = require('gulp-babel');
const concat = require('gulp-concat');
const less = require('gulp-less');
const autoprefixer = require('gulp-autoprefixer');
const minifycss = require('gulp-clean-css');
const gulpif = require('gulp-if');
const connect = require('gulp-connect');
const argv = require('yargs').options('env',{
	alias:'e',
	default:'development',
	describe:'environment: default "development" / "production"',
	type:'string'
}).argv;

const destDir = 'dist';
const DEV = (argv.e === 'development' && true) || false;

let libArray = ['./src/lib/jquery.min.js'];
let jsArray = ['./src/component/*.js'];
let lessArray = ['./src/less/*.less'];

//js文件编译压缩打包
task('minjs', () => {
	return src(jsArray)
		.pipe(gulpif(!DEV, babel()))
		.pipe(gulpif(!DEV, uglify()))
		.pipe(concat('component.js'))
		.pipe(dest(destDir))
		.pipe(gulpif(!DEV, connect.reload()));
});

//less文件合并兼容性处理及压缩
task('mincss', () => {
	return src(lessArray)
		.pipe(concat('component.css'))
		.pipe(gulpif(!DEV,autoprefixer()))
		.pipe(gulpif(!DEV, minifycss()))
		.pipe(dest(destDir))
		.pipe(gulpif(!DEV, connect.reload()));
});

//第三方库原样输出
task('outputlib', () => {
	return src(libArray, {base:'./src'})
		.pipe(dest(destDir));
});

//清空打包目录
task('clean', () => {
	return src(destDir + '/*')
		.pipe(clean());
});

//配置前端服务
task('webserver', () => {
	return connect.server({
		root:'./',
		livereload:true,
		port:8080
	});
});

//实时监听js,less
const watcher = () => {
	watch(lessArray, series(mincss));
	watch(jsArray, series(minjs));
};

task('dev', series('clean', parallel('minjs', 'mincss'), parallel(watcher, 'webserver')));
